package com.fingard.dsp.bank.directbank.pab02;

import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.File;
import java.security.Principal;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

public class PAB02ScheduleTask extends PAB02Base implements IScheduleTask {

	@Override
	public void execTask(TaskTimerSet timerSet) {
		// TODO Auto-generated method stub
		try {
			if (timerSet.taskNameList.toLowerCase().contains("autogettoken")) {
				autoGetToken();
			}
		} catch (Exception ex) {
			this.WriteBankLogLn(ex);
		}
	}

	/**
	 * @param
	 */
	public void autoGetToken() throws Exception {
		Date tmpDateNow = new Date();
		String tmpDateHour = Format.Time8Format.format(tmpDateNow).substring(0,
				5);
		String tmpMinutes = getBankConfig().getValueAsString(
				"taskTimeHourMinutes");
		if (StringHelper.hasAnyChar(tmpMinutes)) {
			for (String tmpMinite : tmpMinutes.split("\\|\\|")) {
				if (tmpDateHour.equals(tmpMinite)) {
					WriteBankLogLn("开始重新同步Token");
					String applicationID = getBankConfig().getMapValueByKey(
							"bankparam", "ApplicationID");
					String tokenPath = getCfgDirectory() + File.separator
							+ applicationID + ".txt";
					String token = FileHelper.readFileText(tokenPath,
							getCharset());
					Map<String, Object> tokenReq = new TreeMap<String, Object>();
					Map<String, Object> map = initSigns(bankFront.ownKeyPassword, bankFront.ownKeyStorePath);
					/* 开放平台门户申请的AppAccessKey */
					tokenReq.put("ApplicationID", applicationID);
					/* 接入方式 固定填写 api */
					tokenReq.put("SDKType", "api");
					tokenReq.put("RandomNumber", get_nonce_str());
					tokenReq.put("cerSeqNo", getcerSeqNo(bankFront.oppCertFilePath));
					tokenReq.put("certPeriod", map.get("DATE").toString());
					JSONObject jsonObject = new JSONObject(tokenReq);
					jsonObject.put("RsaSign", getSign(jsonObject).replaceAll("\r", "")
									.replaceAll("\n", "").replace("+", "%2B")
									.replace("=", "%3D"));
					// 读取证书中的DN与公钥
					Principal dn = (Principal) map.get("DN");
					jsonObject.put("DN", dn.toString().replaceAll("=", "%3D"));
					String publickey = (String) map.get("PK");
					jsonObject.put("PK", publickey.replace("+", "%2B"));
					String[] retRes = sendToBank(jsonObject.toJSONString(),
							bankFront.getUrl("GetTokenUrl"));
					if (retRes[0].length() == 0) {
						JSONObject retJson = JSONObject.parseObject(retRes[1]);
						token = retJson.getString("appAccessToken");
						String retCode = retJson.getString("errorCode");
						String retMsg = retJson.getString("errorMsg");
						if ("OPEN-E-000000".equals(retCode)) {
							if (verifySign(retJson)) {
								FileHelper.writeFile(tokenPath, token,
										getCharset());
								retRes[1] = token;
								WriteBankLogLn("同步Token成功" + token);
							} else {
								WriteBankLogLn("同步Token失败" + retCode + "+"
										+ retMsg);
							}
						} else {
							WriteBankLogLn("同步Token失败" + retCode + "+" + retMsg);
						}
					}

				}
			}
		}
	}
}
